package classloader.hotload;

import java.io.File;
import java.util.*;

/**
 * Created by User on 2018/1/3.
 */
public class ClassFileObserver extends Observable {




    // 监听目录文件修改事件
    static class ClassFileModifiedListener extends Thread {

        String classPath;

        Boolean isStop;

        Long lastLoadTime;

        Map<String, Long> filePathAndLastLoadTime = new HashMap<>();

        public ClassFileModifiedListener(String classPath) {
            this.classPath = classPath;
            isStop = false;
            lastLoadTime = -1L;
            fillFilePathAndLastLoadTime(new File(classPath));
        }

        private void fillFilePathAndLastLoadTime(File file) {
            if (file == null || !file.exists()) return;
            if (file.isFile()) {
                String absolutePath = file.getAbsolutePath();
                if (absolutePath.endsWith(".class")) filePathAndLastLoadTime.put(absolutePath, -1L);
            } else if (file.isDirectory()) {
                for (File f : file.listFiles()) fillFilePathAndLastLoadTime(f);
            }
        }

        @Override
        public void run() {

            while (!isStop && this.isAlive()) {
                synchronized (this) {
                    for (Map.Entry<String, Long> entry : filePathAndLastLoadTime.entrySet()) {
                        String filePath = entry.getKey();
                        Long lastLoadTime = entry.getValue();
                        File file = new File(filePath);
                        if (!file.exists()) continue;
                        if (file.lastModified() != lastLoadTime) {
                            // 加载class文件
                            HotClassLoader hotClassLoader = HotClassLoader.get(classPath);
                            try {
                                Class<?> aClass = hotClassLoader.hotLoadClass(filePath.replace(classPath, ""));
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }





    }
}
